package com.time.workshop.ui.fragment;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.time.workshop.API;
import com.time.workshop.App;
import com.time.workshop.BaseConstant;
import com.time.workshop.BaseFragment;
import com.time.workshop.R;
import com.time.workshop.SuperActivity;
import com.time.workshop.bean.BaseResponse;
import com.time.workshop.bean.OrderCount;
import com.time.workshop.bean.UserInfo;
import com.time.workshop.injector.Injector;
import com.time.workshop.injector.V;
import com.time.workshop.ui.AboutUsActivity;
import com.time.workshop.ui.FeedbackActivity;
import com.time.workshop.ui.LoginActivity;
import com.time.workshop.ui.ModifyPasswordActivity;
import com.time.workshop.ui.OrderListActivity;
import com.time.workshop.utils.ActionSheetDialog;
import com.time.workshop.utils.ActionSheetDialog.OnSheetItemClickListener;
import com.time.workshop.utils.ActionSheetDialog.SheetItemColor;
import com.time.workshop.utils.CommonUtils;
import com.time.workshop.utils.NewToast;
import com.time.workshop.utils.PreferenceUtil;
import com.time.workshop.view.CircularImageView;

/**
 * @author fanbaolong 个人中心
 */
public class MineFragment extends BaseFragment implements OnClickListener
{

	@V
	private ImageView img_mine_back;
	@V
	private RelativeLayout user_login_head_relat, user_to_login_head_relat;
	@V
	private RelativeLayout order_in_process_relat, order_in_delivery_relat, order_in_completed_relat, mine_all_order_relat, mine_pwd_relat, mine_app_detail_relat, mine_about_relat;
	@V
	private Button mine_login_but, exit_but;
	@V
	private TextView mine_order_count, mine_processing_text, mine_delivery_text, mine_completed_text;
	@V
	private CircularImageView user_face_image;

	private static final int IMAGE_REQUEST_CODE = 0; // 相册
	private static final int CAMERA_REQUEST_CODE = 1; // 拍照
	private static final int RESULT_REQUEST_CODE = 2; //

	private class Response extends BaseResponse<OrderCount>
	{
	}

	private Response mOrderCount;

	/** 返回数据总体的实体类 */
	private class Response1 extends BaseResponse<UserInfo>
	{
	};

	private Response1 mUserInfo;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{

		return inflater.inflate(R.layout.activity_mine, container, false);
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState)
	{
		super.onViewCreated(view, savedInstanceState);
		Injector.getInstance().inject(getActivity(), this, view);

		init();

	}

	private void init()
	{

		img_mine_back.setOnClickListener(this);
		mine_all_order_relat.setOnClickListener(this);
		mine_pwd_relat.setOnClickListener(this);
		mine_app_detail_relat.setOnClickListener(this);
		mine_about_relat.setOnClickListener(this);
		exit_but.setOnClickListener(this);
		order_in_process_relat.setOnClickListener(this);
		order_in_delivery_relat.setOnClickListener(this);
		order_in_completed_relat.setOnClickListener(this);
		mine_login_but.setOnClickListener(this);
		user_face_image.setOnClickListener(this);

		// initDate();

	}

	private void initDate()
	{

		RequestParams params = new RequestParams();
		params.addQueryStringParameter("token", PreferenceUtil.getString(getActivity(), BaseConstant.PREF_TOKE_STRING));

		HttpUtils httpUtils = new HttpUtils();
		httpUtils.send(HttpMethod.GET, API.orderCount, params, new RequestCallBack<String>()
		{

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				Log.d("onSuccess==", responseInfo.result);
				try
				{
					JSONObject jsonObject = new JSONObject(responseInfo.result);
					Gson gson = new Gson();

					mOrderCount = gson.fromJson(jsonObject.toString(), Response.class);
					if (mOrderCount.isSuccess())
					{
						int count = mOrderCount.getResult().getDone() + mOrderCount.getResult().getTransact() + mOrderCount.getResult().getUndone();
						mine_processing_text.setText(mOrderCount.getResult().getUndone() + ""); // 待处理
						mine_delivery_text.setText(mOrderCount.getResult().getTransact() + "");// 处理中
						mine_completed_text.setText(mOrderCount.getResult().getDone() + "");// 已完成

						mine_order_count.setText("(" + count + ")"); // 全部订单
						exit_but.setVisibility(View.VISIBLE);
					} else
					{
						if (mOrderCount.getResCode() == 1)
						{
							String name = PreferenceUtil.getString(getActivity(), BaseConstant.PREF_USERNAME_STRING);
							String pwd = PreferenceUtil.getString(getActivity(), BaseConstant.PREF_PASSWORD_STRING);
							if (null != name && null != pwd)
							{
								doLoginRequest(name, pwd);
							}

						} else
						{
							NewToast.makeText(getActivity(), mOrderCount.getMessage());
						}
					}

				} catch (JSONException e)
				{
					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(HttpException error, String msg)
			{
				Log.d("onFailure==", msg);
			}

		});

	}

	/** token过期后再次登录 */
	private void doLoginRequest(String pho, final String pwd)
	{
		mSuperActivity.showDialog(null);
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("username", pho);
		params.addQueryStringParameter("password", pwd);

		HttpUtils httpUtils = new HttpUtils();

		httpUtils.send(HttpMethod.GET, API.login, params, new RequestCallBack<String>()
		{

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				Log.d("onSuccess==", responseInfo.result + "");

				mSuperActivity.dismissLoadingDialog();
				try
				{
					JSONObject jsonObject = new JSONObject(responseInfo.result);
					Gson gson = new Gson();

					mUserInfo = gson.fromJson(jsonObject.toString(), Response1.class);

					Log.d("mUserInfo", mUserInfo.getResult() + "");

					if (mUserInfo.isSuccess())
					{
						// 保存登录返回的Token
						PreferenceUtil.putString(getActivity(), BaseConstant.PREF_TOKE_STRING, mUserInfo.getResult().getTOKEN() + "");
						initDate();
					} else
					{
						NewToast.makeText(getActivity(), mUserInfo.getMessage());
					}
				} catch (JSONException e)
				{
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{
				mSuperActivity.dismissLoadingDialog();
				Log.d("onFailure==", msg + "");
				NewToast.makeText(getActivity(), R.string.login_failure);
			}

		});
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		// 返回
		case R.id.img_mine_back:
			mSuperActivity.menu.showMenu();
			break;
		// 我的订单
		case R.id.mine_all_order_relat:
			if (null == PreferenceUtil.getString(getActivity(), BaseConstant.PREF_TOKE_STRING))
			{
				Intent in = new Intent(getActivity(), LoginActivity.class);
				mSuperActivity.startActivity(in, true);
				return;
			}
			Intent intent = new Intent(getActivity(), OrderListActivity.class);
			intent.putExtra("status", "process");
			mSuperActivity.startActivity(intent, true);
			break;
		// 修改密码
		case R.id.mine_pwd_relat:
			if (null == PreferenceUtil.getString(getActivity(), BaseConstant.PREF_TOKE_STRING))
			{
				Intent in = new Intent(getActivity(), LoginActivity.class);
				mSuperActivity.startActivity(in, true);
				return;
			}
			Intent intentModPwd = new Intent(getActivity(), ModifyPasswordActivity.class);
			mSuperActivity.startActivity(intentModPwd, true);

			break;

		case R.id.mine_app_detail_relat:
			Intent in = new Intent(getActivity(), FeedbackActivity.class);
			mSuperActivity.startActivity(in, true);
			break;

		case R.id.mine_about_relat:
			Intent intentAbout = new Intent(getActivity(), AboutUsActivity.class);
			mSuperActivity.startActivity(intentAbout, true);
			break;

		case R.id.order_in_process_relat:
			Intent intentorder = new Intent(getActivity(), OrderListActivity.class);
			intentorder.putExtra("status", "process");
			mSuperActivity.startActivity(intentorder, true);
			break;

		case R.id.order_in_delivery_relat:
			Intent intentorder1 = new Intent(getActivity(), OrderListActivity.class);
			intentorder1.putExtra("status", "delivery");
			mSuperActivity.startActivity(intentorder1, true);
			break;

		case R.id.order_in_completed_relat:
			Intent intentorder2 = new Intent(getActivity(), OrderListActivity.class);
			intentorder2.putExtra("status", "completed");
			mSuperActivity.startActivity(intentorder2, true);
			break;

		case R.id.exit_but: // 退出登录

			PreferenceUtil.remove(getActivity(), BaseConstant.PREF_TOKE_STRING);

			mine_order_count.setText(""); // 全部订单
			user_login_head_relat.setVisibility(View.GONE);
			user_to_login_head_relat.setVisibility(View.VISIBLE);

			exit_but.setVisibility(View.GONE);
			NewToast.makeText(getActivity(), "已退出登录");

			break;
		// 退出登录
		case R.id.mine_login_but:

			Intent loginIntent = new Intent(getActivity(), LoginActivity.class);
			mSuperActivity.startActivity(loginIntent);

			break;

		case R.id.user_face_image:
			// 设置头像
			new ActionSheetDialog(getActivity()).builder().setCancelable(true).setCanceledOnTouchOutside(true).addSheetItem("拍照", SheetItemColor.Blue, new OnSheetItemClickListener()
			{
				@Override
				public void onClick(int which)
				{
					photo();
				}
			}).addSheetItem("相册", SheetItemColor.Blue, new OnSheetItemClickListener()
			{
				@Override
				public void onClick(int which)
				{
					Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					// i.setPackage("xxxx");// xxxx是具体报名，系统默认的一般是com.android.xx
					startActivityForResult(i, IMAGE_REQUEST_CODE);
				}
			}).show();
			break;

		default:
			break;
		}
	}

	@Override
	public void onResume()
	{
		super.onResume();
		if (null == PreferenceUtil.getString(getActivity(), BaseConstant.PREF_TOKE_STRING))
		{

			user_login_head_relat.setVisibility(View.GONE);
			user_to_login_head_relat.setVisibility(View.VISIBLE);

			exit_but.setVisibility(View.GONE);
		} else
		{
			user_login_head_relat.setVisibility(View.VISIBLE);
			user_to_login_head_relat.setVisibility(View.GONE);

			if (null != PreferenceUtil.getString(getActivity(), BaseConstant.PREF_USER_FACE_IMAGE) && !"".equals(PreferenceUtil.getString(getActivity(), BaseConstant.PREF_USER_FACE_IMAGE)))
			{
				ImageLoader.getInstance().displayImage(PreferenceUtil.getString(getActivity(), BaseConstant.PREF_USER_FACE_IMAGE), user_face_image);
			}

			initDate();
		}

	}

	private String path = "";
	private Uri imageUri;

	public void photo()
	{

		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String state = Environment.getExternalStorageState();
		if (!state.equals(Environment.MEDIA_MOUNTED))
		{
			App.showShortToast("没找到存储卡");
			return;
		}

		File dir = new File(Environment.getExternalStorageDirectory() + "/Workshop");
		if (!dir.exists())
		{
			dir.mkdir();
		}

		File file = new File(Environment.getExternalStorageDirectory() + "/Workshop/", String.valueOf(System.currentTimeMillis()) + ".jpg");
		path = file.getPath();
		App.showLog("path===" + path);
		imageUri = Uri.fromFile(file);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(openCameraIntent, CAMERA_REQUEST_CODE);
	}

	/**
	 * 图片压缩方法实现
	 * 
	 * @param srcPath
	 * @returnc
	 */
	private Bitmap getimage(String srcPath)
	{
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		int hh = 800;// 这里设置高度为800f
		int ww = 480;// 这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww)
		{// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh)
		{// 如果高度高的话根据高度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
	}

	/**
	 * 质量压缩
	 * 
	 * @param image
	 * @return
	 */
	private Bitmap compressImage(Bitmap image)
	{

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 100)
		{ // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset(); // 重置baos即清空baos
			options -= 10; // 每次都减少10
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中

		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		try
		{
			FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Workshop/faceimage.jpg");
			bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
		} catch (Exception e)
		{

		}
		return bitmap;
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri)
	{

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 100);
		intent.putExtra("outputY", 100);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 2);
	}

	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	@SuppressWarnings("deprecation")
	private void getImageToView(Intent data)
	{
		Bundle extras = data.getExtras();
		if (extras != null)
		{
			Bitmap photo = extras.getParcelable("data");
			final Drawable drawable = new BitmapDrawable(photo);
			// 显示图片
			// img_add_task_photo.setImageDrawable(drawable);

			// 此处为上传代码------------------------
			// 为了测试将代码放于此处，到时应该和数据上传发在一起
			((SuperActivity) getActivity()).showLoadingDialog();

			try
			{
				FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Workshop/faceimage.jpg");
				photo.compress(Bitmap.CompressFormat.PNG, 90, out); //

				FinalHttp fh = new FinalHttp();
				AjaxParams params = new AjaxParams();
				params.put("image", new File(Environment.getExternalStorageDirectory() + "/Workshop/faceimage.jpg"));
				params.put("token", PreferenceUtil.getString(getActivity(), BaseConstant.PREF_TOKE_STRING));

				fh.post(API.user_face_img, params, new AjaxCallBack<Object>()
				{

					@Override
					public void onFailure(Throwable t, int errorNo, String strMsg)
					{
						((SuperActivity) getActivity()).dismissLoadingDialog();
						super.onFailure(t, errorNo, strMsg);
						App.showLog("strMsg==" + strMsg);
					}

					@Override
					public void onSuccess(Object t)
					{
						super.onSuccess(t);
						((SuperActivity) getActivity()).dismissLoadingDialog();
						try
						{
							JSONObject jsonObject = new JSONObject(t.toString());
							if (jsonObject.getBoolean("success"))
							{
								user_face_image.setImageDrawable(drawable);
								PreferenceUtil.putString(getActivity(), BaseConstant.PREF_USER_FACE_IMAGE, jsonObject.getString("result"));
								App.showShortToast(jsonObject.getString("message"));
							} else
							{
								App.showShortToast(jsonObject.getString("message"));
							}

						} catch (Exception e)
						{
							e.printStackTrace();
						}

					}

				});

			} catch (Exception e)
			{

			}

		}
	}

	/**
	 * 取得图片回传的数据
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{

		if (resultCode != getActivity().RESULT_CANCELED)
		{
			ContentResolver resolver = getActivity().getContentResolver();
			Bitmap bm = null;
			switch (requestCode)
			{

			// 本地图库
			case IMAGE_REQUEST_CODE:

				startPhotoZoom(data.getData());

				try
				{
					Uri originalUri = data.getData();
					bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);
					String[] proj =
					{ MediaStore.Images.Media.DATA };
					Cursor cursor = getActivity().managedQuery(originalUri, proj, null, null, null);
					int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					cursor.moveToFirst();
					String path = cursor.getString(column_index);
					// 压缩大小
					getimage(path);

				} catch (Exception e)
				{
					Log.w(TAG, e.toString());
				}
				break;
			case CAMERA_REQUEST_CODE:

				if (CommonUtils.hasSDCard())
				{
					startPhotoZoom(imageUri);
					// 压缩大小
					getimage(path);
				} else
				{
					App.showShortToast("没找到存储卡");
				}
				break;
			case RESULT_REQUEST_CODE:
				if (data != null)
				{
					getImageToView(data);
				}
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}
